package cn.itcast.bos.web.action.take_delivery;


import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

//处理kindeditor图片上传管理功能

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototyoe")
public class ImageAction extends BaseAction<Promotion>{

    //属性驱动
    private File imgFile;   //获取文件
    private String imgFileFileName; //获取名字
    private String imgFileContentType;  //获取文件类型

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }
    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }
    public void setImgFileContentType(String imgFileContentType) {
        this.imgFileContentType = imgFileContentType;
    }

    @Action(value = "image_upload",results = {@Result(name = "success",type = "json")})
    public String upload() throws IOException {
        System.out.println(imgFile);
        System.out.println(imgFileFileName);
        System.out.println(imgFileContentType);

        //存储文件的绝对路径
        String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
        //相对路径
        String saveUrl = ServletActionContext.getRequest().getContextPath()+"/upload/";
        //生成随机图片名
        UUID uuid = UUID.randomUUID();
        String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
        String randomFileName=uuid+ext;

        //创建上传的文件保存方法
        File file = new File(savePath + "/" + randomFileName);
//        使用工具类复制缓存的文件到指定位置
        FileUtils.copyFile(imgFile,file);
        System.out.println(file.getAbsolutePath());

        //编写方法通知浏览器文件上传成功
        HashMap<String, Object> map = new HashMap<>();
        map.put("error",0);
        map.put("url",saveUrl+randomFileName);

        ActionContext.getContext().getValueStack().push(map);
        return SUCCESS;
    }

}
